var access = require('../access');
var auth = require('../auth');

app.get('/checkin', access.admin, function(request, response) {
	model.Event.find().sort('when', 1).run(function(e, events) {
		if (e) {
			response.render('error.jade', {
				title : 'Event Error',
				error : e,
				pretty : true
			});
		} else {
			response.render('Checkin/setup.jade', {
				title : 'Check In',
				events : events,
				live : request.session.checkin || false,
				pretty : true
			});
		}
	});
});

app.get('/checkin/start/:event', access.admin, function(request, response) {
	request.session.checkin = true;
	request.session.event = request.params.event;
	response.redirect('/checkin/live');
});

app.get('/checkin/live', access.admin, function(request, response) {
	if (request.session.checkin) {

		model.Event.findOne({
			_id : request.session.event
		}, function(e, event) {
			if (e) {
				response.render('error.jade', {
					title : 'Event Error',
					error : e,
					pretty : true
				});
			} else if (event) {

				auth.facebook(request, response, function(user) {
					if (user) {
						var checkedIn = false;
						user.events.forEach(function(event) {
							if (event == request.session.event) {
								checkedIn = true;
							}
						});

						if (!checkedIn) {
							user.events.push(request.session.event);
						}

						user.save(function(e) {
							if (e) {
								response.render('error.jade', {
									title : 'Check In Error',
									error : e,
									pretty : true
								});
							} else {
								model.User.findOne({
									_id : user._id
								}).populate('events').run(function(e, user) {
									response.render('Checkin/live.jade', {
										title : 'Check In',
										profile : user,
										event : event,
										pretty : true
									});
								});
							}
						}); // user.save(function(e)
					} else { // if (user)
						response.render('Checkin/live.jade', {
							title : 'Checkin',
							profile : undefined,
							event : event,
							pretty : true
						});
					} // if (user)
				}, false); // auth.facebook(request, response, function(user) 
			} else { //else if (event)
				response.render('error.jade', {
					title : 'Check In Error',
					error : 'Undefined Event',
					pretty : true
				});
			}
		}); // model.Event.findOne({
	} else { // if (request.session.checkin)
		response.redirect('/checkin');
	}
});

app.get('/checkin/stop', access.admin, function(request, response) {
	request.session.checkin = false;
	request.session.event = undefined;
	response.redirect('/checkin');
});